package com.lin.generate.config.datasource;

import com.lin.generate.common.dto.UserDataSourceKey;
import com.lin.generate.common.utill.SpringUtils;
import com.lin.generate.service.IZlDataSourceConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

/**
 * @description TODO
 * @Author: z156940l@outlook.com
 * @className DataSourceComponent
 * @Date: 2023/6/1 23:28
 */
@Component
public class DataSourceComponent {

    @Autowired
    IZlDataSourceConfigService iDataSourceConfigService;
    @Autowired
    DataSourceBean dataSourceBean;

    private static DataSourceComponent dataSourceComponent;
    @PostConstruct
    public void init() {
        dataSourceComponent = this;
        dataSourceComponent.iDataSourceConfigService = this.iDataSourceConfigService;
        dataSourceComponent.dataSourceBean = this.dataSourceBean;
    }

    public static DataSourceBean getDataSourceBean() {
        String userId = DynamicDataSourceContextHolder.getUserId();
        if(userId != null) {
            UserDataSourceKey record = new UserDataSourceKey();
            record.setUserId(userId);
            return dataSourceComponent.iDataSourceConfigService.getDataSource(record);
        }
        return dataSourceComponent.dataSourceBean;
    }


    /**
     * 查询指定用户的数据源
     * @param userId
     * @return
     */
    public static DataSourceBean getDataSourceBean(String userId) {
        if(userId != null&& !userId.isEmpty()) {
            UserDataSourceKey record = new UserDataSourceKey();
            record.setUserId(userId);
            return dataSourceComponent.iDataSourceConfigService.getDataSource(record);
        }
        return null;
    }

    /**
     * 获取默认的数据源
     * @return
     */
    private static DataSourceBean defaultDataSourceBean() {
        return new DataSourceBean();
    }
}
